<template>
    <el-card class="box-card">
        <!-- 卡片顶部添加品牌按钮 -->
        <el-button type="primary" icon="Plus" @click="addTradMark">添加品牌</el-button>
        <!-- 表格组件,用于展示已有的品牌数据 -->
        <!-- 
            table
            ---border：可以设置表格纵向边框
            table-column
            ---label：某一个列表
            ---width：设置这列宽度
            ---align：设置这列对齐方式
         -->
        <el-table :data="trademarkArr" style="margin: 10px;" border >
            <el-table-column  label="序号" width="80px" align="center" type="index"/>
            <el-table-column  label="品牌名称" >
                <template #="{row,$index}">
                    <pre style="color: red;">{{ row.tmName }}</pre>
                </template>
            </el-table-column>
            <el-table-column prop="" label="品牌LOGO">
                <template #="{row,$index}">
                    <img :src="row.logoUrl" style="width: 100px; height: 100px;" alt="未有图片">
                </template>
            </el-table-column>
            <el-table-column  label="品牌操作" >
                <template #default="{row,column: any, $index: number }">
                    <el-button type="primary" size="small" icon="Edit" @click="updateTradeMark(row)"></el-button>
                    <el-popconfirm :title="`您确定要删除${row.tmName}?`" width="250px" icon="Delete" @confirm="removeTradeMark(row.id)">
                        <template #reference>
                            <el-button icon="Delete" type="primary" size="small"></el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页器组件
            pagination
                v-model:current-page:设置分页器当前的页码
                v-model:page-size:设置每一页展示数据的条数
                page-sizes:用于设置下拉菜单数据
                background:设置分页器按扭的颜色
                laout:可以设置分页器六个子组件布局调整
         -->
            <el-pagination
            @current-change="changeCurrentPage"
            @size-change="changePageSize"
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[3, 5, 7, 9]"
            :background="true"
            layout=" prev, pager, next, jumper, ->,sizes, total"
            :total="total"
            />
    </el-card>
    <!-- 对话框组件:在添加品牌与修改已有品牌的业务的时候使用的结构 -->
    <!-- v-model控制对话框的显示与隐藏
        title: 设置对话框左上角的标题
     -->
    <el-dialog v-model="dialogFormVisible" :title="trademarkParams.id?'修改品牌':'添加品牌'">
        <el-form style="width: 80%;" :model="trademarkParams" :rules="rules" ref="formRef">
            <el-form-item label="品牌名称" label-width="100px" prop="tmName" >
                <el-input placeholder="请您输入品牌名称" v-model="trademarkParams.tmName" />
            </el-form-item>
            <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
                <el-upload
                    class="avatar-uploader"
                    action="/api/admin/product/fileUpload"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                >
                    <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="cancel">取消</el-button>
                <el-button type="primary" @click="confirm">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup lang="ts">
import { ref,onMounted ,reactive,nextTick} from 'vue';
import { reqHasTrademark,reqAddOrUpdateTrademark,reqDeleteTrademark } from '@/api/product/trademark';
import type { Records,TradeMarkResponseData,TradeMark } from '@/api/product/trademark/type';
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus';
//控制对话框的显示与隐藏属性
let dialogFormVisible=ref<boolean>(false);


let currentPage=ref(1);//当前页码
let pageSize=ref(3);//每一页显示多少条数据
//存储已有品牌数据总数
let total=ref(0);
//存储已有品牌数据
let trademarkArr=ref<Records>([]);

//收集新增品牌数据
let trademarkParams=reactive<TradeMark>({
    tmName: '',
    logoUrl: ''
})

//获取el-form组件实例
let formRef=ref();








//获取已有品牌的接口封装为一个函数
const getHasTrademark=async()=>{
    let result: TradeMarkResponseData= await reqHasTrademark(currentPage.value,pageSize.value);
    console.log('获取品牌')
    console.log(result);
    if(result.code==200){
        //存储已有品牌的总个数
        total.value=result.data.total;
        trademarkArr.value=result.data.records;
    }

}
//当下拉菜单发生变化的时候会触发
const changePageSize=()=>{
    currentPage.value=1
    //当前分页器页码发生变化时请求数据
    getHasTrademark();
}
//组件挂载完毕后，发请求获取品牌数据
onMounted(()=>{
    getHasTrademark();
})

//分页器当前页码发生变化的时候会触发回传当前页码
const changeCurrentPage=()=>{
    
   //当前页码发生变化的时候再次发请求获取对应的已有品牌的数据展示
   getHasTrademark();
}


//添加品牌按钮的回调
const addTradMark=()=>{
    //对话框显示

    


    Object.assign(trademarkParams,{
        id: '',
        tmName: '',
        logoUrl: ''
    });

    nextTick(()=>{
        formRef.value.clearValidate();
    })


    dialogFormVisible.value=true;
}

//修改已有品牌按钮的回调
const updateTradeMark=(row:TradeMark)=>{
    //展示已有品牌的数据

    nextTick(()=>{
        formRef.value.clearValidate();
    })
    trademarkParams.tmName=row.tmName;
    trademarkParams.logoUrl=row.logoUrl
    trademarkParams.id=row.id
    dialogFormVisible.value=true;
}

//对话框底部取消按钮
const cancel=()=>{
    dialogFormVisible.value=false;
}

//对话框底部确定
const confirm=async ()=>{


//在发请求之前对整个表单进行校验
    //调用这个方法进行全部表单校验，如果检验全部通过，在执行后面的语法
    await formRef.value.validate();

    let result= await reqAddOrUpdateTrademark(trademarkParams);
    console.log("修改|添加品牌")
    console.log(result);
    if(result.code==200){
        //弹出提示信息
        ElMessage({
            type: 'success',
            message:trademarkParams.id?'修改品牌成功':'添加品牌成功'
        });
        //再次发请求获取已有品牌数据
        getHasTrademark();
    }
    else{
        ElMessage({
            type: 'error',
            message:trademarkParams.id?'修改品牌失败':'添加品牌失败'
        });
    }




    dialogFormVisible.value=false;
}

//上传图片之前触发的钩子函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type == 'image/jpeg' || rawFile.type=='image/png'||rawFile.type=='image/gif') {
        if(rawFile.size<=1024*1024*4){
            return true;
        }
        else{
            ElMessage.error("上传文件大小应小于4M");
            return false;
        }
  } else {
    ElMessage.error("上传的文件格式错误");
    return false;
  }
}

//图片上传成功的钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
    //图片上传成功清除掉对应图片校验结果

    formRef.value.clearValidate('logoUrl');

    trademarkParams.logoUrl=response.data;



}


//品牌校验自定义规则
const validatorTmName=(rule: any, value: any, callback: any)=>{
    if(value.length>=2){
        callback();
    }
    else{
        callback(new Error("品牌名称位数大于等于两位"))
    }
}

//品牌logo图片自定义校验规则
const validatorLogoUrl=(rule: any, value: any, callback: any)=>{

    if(value){
        callback();
    }
    else{
        callback(new Error('没有图片'))
    }

}



//表单校验规则对象
const rules={
    tmName: [
        //required:这个字段必须要校验，表单项前面出来五角星
        //trigger:代表触发校验规则时机
        {required: true,trigger: 'blur',validator:validatorTmName}
    ],
    logoUrl: [
        {required: true,trigger: 'blur',validator: validatorLogoUrl}
    ]
}



//气泡确认框按钮回调
const removeTradeMark=async (id: number)=>{
     let result= await reqDeleteTrademark(id);
     console.log("删除数据")
     console.log(result);
     if(result.code==200){
        ElMessage.success("删除品牌成功");
        //再次获取品牌数据
        getHasTrademark();
     }
     else{
        ElMessage.error("删除品牌失败");
     }
}









</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>